<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
      active-color="#13ce66">
      是否开启拖拽
    </el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree :data="menus" :props="defaultProps"
             :expand-on-click-node="false"
             :show-checkbox="true"
             node-key="catId"
             :draggable="draggable"
             :allow-drop="allowDrop"
             @node-drop="handleDrop"
             ref="menuTree"
             :default-expanded-keys="expandedKey">
    <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level<=2"
            type="text"
            size="mini"
            @click="() => append(data)">
            新增
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => edit(data)">
            修改
          </el-button>
          <el-button
            v-if="node.childNodes.length==0"
            type="text"
            size="mini"
            @click="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%">
      <el-form label-width="80px" :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="category.productUnit" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'category',
  data () {
    return {
      pCid: 0,
      draggable: false,
      title: '',
      dialogType: '', // edit,add
      menus: [],
      expandedKey: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dialogVisible: false,
      category: {
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: '',
        productUnit: ''
      },
      maxLevel: 0,
      updateNodes: []
    }
  },
  methods: {
    getMenuData () {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({data}) => {
        this.menus = data.data
      })
    },
    append (data) {
      this.dialogType = 'add'
      this.dialogVisible = true
      this.category.parentCid = data.catId
      this.category.name = ''
      this.category.productUnit = ''
      this.category.icon = ''
      this.category.catLevel = data.catLevel * 1 + 1
      this.category.catId = null
    },
    remove (node, data) {
      let {catId} = data
      this.$confirm(`是否删除当前菜单[${data.name}]?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData([catId], false)
        }).then(({data}) => {
          this.$message({
            type: 'success',
            message: '菜单删除成功'
          })
          // 刷新出新菜单
          this.getMenuData()
          this.expandedKey = [node.parent.data.catId]
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    edit (data) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({data}) => {
        // console.log(data.data)
        this.category.name = data.data.name
        this.category.icon = data.data.icon
        this.category.productUnit = data.data.productUnit
        this.category.catId = data.data.catId
        this.expandedKey = [data.data.parentCid]
      })
    },
    editCategory () {
      // console.log('editCategory', this.category)
      let {catId, name, icon, productUnit} = this.category
      let postData = {catId, name, icon, productUnit}
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData(postData, false)
      }).then(({data}) => {
        this.$message({
          type: 'success',
          message: '修改成功'
        })
        this.dialogVisible = false
        this.getMenuData()
        this.expandedKey = [this.category.parentCid]
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '修改失败'
        })
      })
    },
    // 添加三级分类
    addCategory (data) {
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({data}) => {
        this.$message({
          type: 'success',
          message: '添加成功'
        })
        this.dialogVisible = false
        this.getMenuData()
        this.expandedKey = [this.category.parentCid]
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '添加失败'
        })
      })
    },
    submitData () {
      if (this.dialogType === 'add') {
        this.title = '添加分类'
        this.addCategory()
      } else {
        this.title = '修改分类'
        this.editCategory()
      }
    },
    allowDrop (draggingNode, dropNode, type) {
      // console.log(draggingNode, dropNode, type)
      this.maxLevel = draggingNode.data.catLevel
      this.countNodeLevel(draggingNode.data)
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1
      // console.log('deep', deep)
      // this.maxLevel
      if (type === 'inner') {
        return (deep + dropNode.level) <= 3
      } else {
        return (deep + dropNode.parent.level) <= 3
      }
    },
    countNodeLevel (node) {
      if (node.children != null && node.children.length !== 0) {
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxLevel) {
            this.maxLevel = node.children[i].catLevel
          }
          this.countNodeLevel(node.children[i])
        }
      }
    },
    handleDrop (draggingNode, dropNode, dropType, ev) {
      // console.log('tree drop: ', dropNode, dropType)
      let pCid = 0
      let siblings = null
      this.updateNodes = []
      if (dropType === 'before' || dropType === 'after') {
        pCid = dropNode.data.parentCid
        siblings = dropNode.parent.childNodes
      } else {
        pCid = dropNode.data.catId
        siblings = dropNode.childNodes
      }
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId === draggingNode.data.catId) {
          let catLevel = draggingNode.level
          if (siblings[i].level !== draggingNode.level) {
            catLevel = siblings[i].level
            this.updateChildNodeLevel(siblings[i])
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel
          })
        } else {
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i})
        }
      }
      this.pCid = pCid
      // console.log('updateNodes', this.updateNodes)
    },
    updateChildNodeLevel (node) {
      if (node.childNodes.length === 0) return
      for (let i = 0; i < node.childNodes.length; i++) {
        let cNode = node.childNodes[i].data
        this.updateNodes.push({catId: cNode.catId, catLevel: node.childNodes[i].level})
        this.updateChildNodeLevel(node.childNodes[i])
      }
    },
    batchSave () {
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({data}) => {
        this.pCid = 0
        this.dialogVisible = false
        this.getMenuData()
        this.$message({
          type: 'success',
          message: '更新成功'
        })
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '更新失败'
        })
      })
    },
    batchDelete () {
      let checkedNodes = this.$refs.menuTree.getCheckedNodes(false, false)
      let catIds = []
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId)
      }
      this.$confirm(`是否批量删除菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(catIds, false)
        }).then(({data}) => {
          this.$message.success('删除成功')
          this.getMenuData()
        }).catch(() => {
          this.$message.error('删除失败')
        })
      })
    }
  },
  created () {
    this.getMenuData()
  }
}
</script>

<style scoped>

</style>
